#include "HashSet.h"
#include <stdlib.h>
#include <stdio.h>

// 哈希函数
static int hash(int key, int capacity) {
    return key % capacity;
}

// 创建哈希集合
HashSet* create_hashset(int capacity) {
    HashSet* set = (HashSet*)malloc(sizeof(HashSet));
    if (set == NULL) {
        perror("Failed to create hashset");
        return NULL;
    }
    set->buckets = (Node**)calloc(capacity, sizeof(Node*));
    if (set->buckets == NULL) {
        perror("Failed to create hashset buckets");
        free(set);
        return NULL;
    }
    set->capacity = capacity;
    set->size = 0;
    return set;
}

// 销毁哈希集合
void destroy_hashset(HashSet* set) {
    if (set == NULL) return;
    hashset_clear(set);
    free(set->buckets);
    free(set);
}

// 插入元素
bool hashset_add(HashSet* set, int key) {
    int index = hash(key, set->capacity);
    Node* node = set->buckets[index];
    while (node != NULL) {
        if (node->key == key) {
            return false; // 元素已存在
        }
        node = node->next;
    }
    node = (Node*)malloc(sizeof(Node));
    if (node == NULL) {
        perror("Failed to insert into hashset");
        return false;
    }
    node->key = key;
    node->next = set->buckets[index];
    set->buckets[index] = node;
    set->size++;
    return true;
}

// 查找元素
bool hashset_contains(HashSet* set, int key) {
    int index = hash(key, set->capacity);
    Node* node = set->buckets[index];
    while (node != NULL) {
        if (node->key == key) {
            return true;
        }
        node = node->next;
    }
    return false;
}

// 删除元素
bool hashset_remove(HashSet* set, int key) {
    int index = hash(key, set->capacity);
    Node* node = set->buckets[index];
    Node* prev = NULL;
    while (node != NULL) {
        if (node->key == key) {
            if (prev == NULL) {
                set->buckets[index] = node->next;
            } else {
                prev->next = node->next;
            }
            free(node);
            set->size--;
            return true;
        }
        prev = node;
        node = node->next;
    }
    return false;
}

// 清空哈希集合
void hashset_clear(HashSet* set) {
    for (int i = 0; i < set->capacity; i++) {
        Node* node = set->buckets[i];
        while (node != NULL) {
            Node* tmp = node;
            node = node->next;
            free(tmp);
        }
        set->buckets[i] = NULL;
    }
    set->size = 0;
}

// 获取哈希集合大小
int hashset_size(HashSet* set) {
    return set->size;
}

// 遍历哈希集合
void hashset_iterate(HashSet* set, void (*func)(int key)) {
    for (int i = 0; i < set->capacity; i++) {
        Node* node = set->buckets[i];
        while (node != NULL) {
            func(node->key);
            node = node->next;
        }
    }
}
